<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 商品模型
 *
 * @author      Eden
 * @datetime    2016/12/14 20:27
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Goods_Model extends ADM_Model
{

    // 状态
    private $status = null;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 商品列表
     * @param int $offset
     * @param int $limit
     * @param array $where
     * @return array|bool
     */
    public function getGoodsLists($offset = 0, $limit = 20, $where = array())
    {
        $gDb = clone($this->db);

        if (!empty($where)) {
            $gDb->where($where);
        }

        $gDb->where('bg.status != -1');
        $total = $gDb->count_all_results('base_goods as bg');
        if ($total == 0) {
            return false;
        }

        $db = clone($this->db);
        $db->where('bg.status != -1');
        if (!empty($where)) {
            $db->where($where);
        }
        $db->limit($limit, $offset);
        $db->select('bg.id, bg.baseId, bg.categoryId, bg.goodsName, bg.description, bg.expressWeight, bg.thumb,
        bg.bannerThumb, bg.recommendThumb, bg.liveUrl, bg.streamId, bg.content, bg.pv, bg.likes, bg.stars, bg.comments,
        bg.price, bg.minPrice, bg.maxPrice, bg.minPurPrice, bg.maxPurPrice, bg.stock, bg.unit, bg.created, bg.createdBy, bg.status, bg.activity, bc.name as categoryName, b.name as baseName');
        $db->join('base_category as bc', 'bc.id = bg.categoryId');
        $db->join('base as b', 'b.id=bg.baseId');
        $db->order_by('bg.id', 'DESC');
        $q = $db->get('base_goods as bg');
        $rows = $q->result_array();
        if (empty($rows)) {
            return false;
        }

        foreach($rows as &$row) {
            $thumb = !empty($row['bannerThumb']) ? $row['bannerThumb'] : $row['thumb'];
            $row['thumb'] = thumb($thumb, 200, 200);
            $row['price'] = money_format("%i", $row['price']);
            $row['minPrice'] = money_format("%i", $row['minPrice'] / 100);
            $row['maxPrice'] = money_format("%i", $row['maxPrice'] / 100);
            $row['minPurPrice'] = money_format('%i', $row['minPurPrice'] / 100);
            $row['maxPurPrice'] = money_format('%i', $row['maxPurPrice'] / 100);
        }

        /*
        echo '<pre>';
        print_r($rows);
        die;
        */

        return array(
            'total' => intval($total),
            'data' => $rows
        );
    }

    /**
     * 添加商品
     * @param array $params
     * @return bool
     */
    public function addGoods($params = array())
    {
        $data = $this->_formatData($params, 'add');
        $this->db->insert('base_goods', $data);
        $id = $this->db->insert_id();

        if (empty($id)) {
            return false;
        }

        $rules = [];
        foreach ($params['rules'] as $item) {
            $oldPrice = value($item, 'ruleOldPrice', 0);
            $salePrice = value($item, 'ruleNewPrice', 0);
            $purchaserPrice = value($item, 'rulePurchaserPrice', 0);
            $rules[] = [
                'goods_id' => $id,
                'name' => value($item, 'ruleName', ''),
                'stock' => value($item, 'ruleStore', 0),
                'oldPrice' => intval($oldPrice * 100),
                'salePrice' => intval($salePrice * 100),
                'purchaserPrice' => intval($purchaserPrice * 100),
                'weight' => value($item, 'ruleGoodsWeight', 0),
                'expressWeight' => value($item, 'ruleExpressWeight', 0),
            ];
        }
        $this->db->insert_batch('base_goods_rule', $rules);
        unset($item);

        // thumbs
        $thumbs = [];
        foreach ($params['thumbLists'] as $item) {
            $thumbs[] = [
                'goods_id' => $id,
                'thumb' => value($item, 'key', '')
            ];
        }
        $this->db->insert_batch('base_goods_thumb', $thumbs);

        return true;
    }

    /**
     * 修改商品
     * @param array $params
     * @return bool
     */
    public function editGoods($params = array())
    {
        $data = $this->_formatData($params, 'edit');
        $db = clone($this->db);
        $q = $db->get_where('base_goods', array('id' => $params['goodsId']));
        if (!$q->row_array()) {
            $this->setError(['商品不存在']);
            return false;
        }

        $db->where(array('id' => $params['goodsId']));
        $db->update('base_goods', $data);

        // rules 表
        $old_ruleids = $new_rules = [];
        foreach ($params['rules'] as $item) {
            if (!empty($item['id'])) {
                $old_ruleids[] = $item['id'];
            } else {
                $oldPrice = value($item, 'ruleOldPrice', 0);
                $salePrice = value($item, 'ruleNewPrice', 0);
                $purchaserPrice = value($item, 'rulePurchaserPrice', 0);
                $new_rules[] = [
                    'goods_id' => $params['goodsId'],
                    'name' => value($item, 'ruleName', ''),
                    'stock' => value($item, 'ruleStore', 0),
                    'oldPrice' => intval($oldPrice * 100),
                    'salePrice' => intval($salePrice * 100),
                    'purchaserPrice' => intval($purchaserPrice * 100),
                    'weight' => value($item, 'ruleGoodsWeight', 0),
                    'expressWeight' => value($item, 'ruleExpressWeight', 0),
                ];
            }
        }
        unset($item);

        // 把不要的删除,再把新的添加进去
        if (!empty($old_ruleids)) {
            $ruleDb = clone($this->db);
            $ruleDb->where('goods_id', $params['goodsId']);
            $ruleDb->where_not_in('id', $old_ruleids);
            $ruleDb->update('base_goods_rule', ['status' => -1]);
            unset($ruleDb);
        }

        if (!empty($new_rules)) {
            $ruleDb = clone($this->db);
            $ruleDb->insert_batch('base_goods_rule', $new_rules);
        }

        // thumb 表
        $old_thumbids = $new_thumbs = [];
        foreach($params['thumbLists'] as $item) {
            if (!empty($item['id'])) {
                $old_thumbids[] = $item['id'];
            } else {
                $new_thumbs[] = [
                    'goods_id' => $params['goodsId'],
                    'thumb' => value($item, 'key', '')
                ];
            }
        }

        if (!empty($old_thumbids)) {
            $thumbdb = clone($this->db);
            $thumbdb->where('goods_id', $params['goodsId']);
            $thumbdb->where_not_in('id', $old_thumbids);
            $thumbdb->delete('base_goods_thumb');
            unset($thumbdb);
        }

        if (!empty($new_thumbs)) {
            $thumbdb = clone($this->db);
            $thumbdb->insert_batch('base_goods_thumb', $new_thumbs);
        }

        return $db->affected_rows();
    }

    /**
     * 设置状态
     * @param $status
     */
    public function setStauts($status)
    {
        $this->status = $status == 'up' ? 1 : 0;
    }

    /**
     * 修改商品状态
     * 删除商品,不作物理删除
     * @param $goodsId
     * @return bool
     */
    public function changeGoods($goodsId, $type = 'delete')
    {
        $db = clone($this->db);
        $q = $db->get_where('base_goods', array('id' => $goodsId));
        if (!$q->row_array()) {
            $this->setError('商品不存在');
            return false;
        }

        $this->db->where('id', $goodsId);

        if ($type == 'delete') {
            $status = -1;
        } else {
            $status = is_null($this->status) || $this->status == 0 ? 0 : 1;
        }
        $this->db->update('base_goods', array('status' => $status));
        return $this->db->affected_rows();
    }

    /**
     * 获取商品信息
     * @param $goodsId
     * @return mixed
     */
    public function getGoodsInfo($goodsId)
    {
        $gDb = clone($this->db);
        $q = $gDb->select('g.id, g.baseId, g.categoryId, g.goodsName,
            g.expressWeight, g.streamId, g.liveUrl, g.description, g.thumb, g.bannerThumb, g.recommendThumb,
            g.content, g.stars, g.price, g.expType, g.expAmount, g.stock, g.unit, g.activity')
            ->where(array('g.id' => $goodsId))
            ->from('base_goods as g')
            ->get();
        $row = $q->row_array();
        if (empty($row)) {
            $this->setError('商品不存在');
        }
        // setlocale(LC_MONETARY,"");
        $row['id'] = intval($row['id']);
        $row['baseId'] = intval($row['baseId']);
        $row['categoryId'] = intval($row['categoryId']);
        $row['stars'] = intval($row['stars']);
        $row['stock'] = intval($row['stock']);
        $row['fullPath'] = thumb($row['thumb']);
        $row['recommendFullPath'] = thumb($row['recommendThumb'], 150, 200);
        $row['bannerFullPath'] = thumb($row['bannerThumb'], 320, 180);
        $row['price'] = money_format("%i", $row['price']);
        $row['rules'] = [];
        $row['thumbLists'] = [];
        $row['expType'] = intval($row['expType']);
        $row['expAmount'] = money_format('%i', $row['expAmount'] / 100);
        $row['activity'] = $row['activity'] == 1 ? "on" : "off";

        // get rules
        $rDb = clone($this->db);
        $rQuery = $rDb->get_where('base_goods_rule', ['goods_id' => $goodsId, 'status' => 6]);
        $rules = $rQuery->result_array();
        if (!empty($rules)) foreach($rules as &$item) {
            $item['stock'] = intval($item['stock']);
            $item['oldPrice'] = money_format('%i', $item['oldPrice'] / 100);
            $item['salePrice'] = money_format('%i', $item['salePrice'] / 100);
            $item['purchaserPrice'] = money_format('%i', $item['purchaserPrice'] / 100);
        }
        $row['rules'] = $rules;

        // get thumb
        $tDb = clone($this->db);
        $tQuery = $tDb->get_where('base_goods_thumb', ['goods_id' => $goodsId]);
        $thumbs = $tQuery->result_array();
        if (!empty($thumbs)) foreach ($thumbs as &$item) {
            $item['thumb_view'] = thumb($item['thumb'], 100, 100);
        }
        $row['thumbLists'] = $thumbs;

        return $row;
    }

    /**
     * 设置修改时间
     * @param $params
     * @param string $type
     * @return array
     */
    private function _formatData($params, $type= 'add')
    {
        $dateTime = dateTime();
        $adminId = adminId();

        // 总库存
        $stock = 0;
        $prices = [];
        $purPrices = [];
        foreach ($params['rules'] as $item) {
            $stock += $item['ruleStore'];
            $prices[] = intval($item['ruleNewPrice'] * 100);
            $purPrices[] = intval($item['rulePurchaserPrice'] * 100);
        }

        $data = array(
            'categoryId' => value($params, 'categoryId', 0),
            'baseId' => value($params, 'baseId', 0),
            'goodsName' => value($params, 'goodsName', ''),
            'thumb' => value($params, 'thumb', ''),
            'bannerThumb' => value($params, 'bannerThumb', ''),
            'recommendThumb' => value($params, 'recommendThumb', ''),
            'streamId' => value($params, 'streamId', 0),
            'liveUrl' => value($params, 'liveUrl', ''),
            'content' => value($params, 'content', ''),
            'stars' => value($params, 'stars', 0),
            'price' => isset($params['price']) ? money_format('%i', $params['price']) : 0,
            'minPrice' => min($prices),
            'maxPrice' => max($prices),
            'minPurPrice' => min($purPrices),
            'maxPurPrice' => max($purPrices),
            'stock' => $stock,
            'expressWeight' => value($params, 'expressWeight', 0),
            'unit' => value($params, 'unit', '个'),
            'modified' => $dateTime,
            'modifiedBy' => $adminId,
            'description' => value($params, 'description'),
            'expType' => value($params, 'expType', 1),
            'expAmount' => value($params, 'expAmount', 0),
            'activity' => isset($params['activity']) && $params['activity'] == "on" ? 1 : 0,
        );

        if (!empty($params['thumbWidth']) && !empty($params['thumbHeight'])) {
            $data = array_merge($data, [
                'thumbWidth' => intval($params['thumbWidth']),
                'thumbHeight' => intval($params['thumbHeight']),
            ]);
        }

        if ($type == 'add') {
            return array_merge($data, array(
                'pv' => 0,
                'comments' => 0,
                'likes' => 0,
                'allowComment' => 1,
                'created' => $dateTime,
                'createdBy' => $adminId
            ));
        }

        return $data;
    }

    /**
     * 最新产品
     * @param int $limit
     * @return mixed
     */
    public function getLatestProducts($limit = 20)
    {
        $query = $this->db
            ->select('id, goodsName, thumb, minPrice, description')
            ->order_by('created', 'DESC')
            ->limit($limit)
            ->get_where('base_goods', ['status' => 1]);
        return $query->result_array();
    }

    /**
     * 获取详情
     * @param $goodsId
     * @return mixed
     */
    public function getDetails($goodsId)
    {
        $db = clone($this->db);
        $query = $db->get_where('base_goods', ['id' => $goodsId]);
        return $query->row_array();
    }

}
